using System;
using System.Data.SqlClient;
using HashFoo.Core;

namespace HashFoo.SqlServer
{
    /// <summary>
    /// Database utilities for testing.
    /// </summary>
    public static class DbTestingUtil
    {
        /// <summary>
        /// Will attempt to do a simple drop and recreate of a database
        /// </summary>
        /// <param name="dbName">The name of the database</param>
        /// <param name="masterConnectionString">The connection string to the database server.  Defaults to (local) with integrated security.</param>
        public static void NukeMsSqlDatabase(
            string dbName,
            string masterConnectionString = "Data Source=(local);Initial Catalog=master;Integrated Security=True;Pooling=False")
        {
            // we assume we're using sql
            //  we could also set "Pooling=false" in the connection string in the mock assembly
            //  however, that may mess with any sort of load tests we'd want to do in the future.
            SqlConnection.ClearAllPools();

            using (var dbConn = new SqlConnection(masterConnectionString))
            {
                try
                {
                    dbConn.Open();

                    using (var command = dbConn.CreateCommand())
                    {
                        command.CommandText =
                                ("if DB_ID('{0}') is not null\n" +
                                "ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\n\n" +
                                "if DB_ID('{0}') is not null\n" +
                                "drop database [{0}];\n\n" +
                                "if DB_ID('{0}') is null\n" +
                                "create database [{0}];").DoFormat(dbName);

                        command.ExecuteNonQuery();
                    }
                }
                catch (SqlException ex)
                {
                    Console.Error.WriteLine(ex);
                    throw;
                }
                finally
                {
                    dbConn.Close();
                }
            }
        }
    }
}